package cn.emall.cart.controller;

import cn.emall.cart.service.CartService;
import cn.emall.pojo.TbItem;
import cn.emall.pojo.TbUser;
import cn.emall.service.ItemService;
import cn.emall.utils.CookieUtils;
import cn.emall.utils.EmallResult;
import cn.emall.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 购物车处理Controller
 */
@Controller
public class CartController {

    @Autowired
    private ItemService itemService;
    @Autowired
    private CartService cartService;
    @Value("${COOKIE_CART_EXPIRE}")
    private Integer COOKIE_CART_EXPIRE;

    /**
     * 添加购物车
     * @param itemId 商品id
     * @param num 要添加的数量
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/cart/add/{itemId}")
    public String addCart(@PathVariable Long itemId, @RequestParam(defaultValue = "1")Integer num,
                          HttpServletRequest request, HttpServletResponse response){
        //判断用户是否登录
        TbUser user = (TbUser) request.getAttribute("user");
        //如果是登录状态把购物车写入到redis
        if(user != null){
            //保存到redis服务器
            cartService.addCart(user.getId(),itemId,num);
            //返回逻辑视图
            return "cartSuccess";
        }
        //如果未登录使用cookie
        //根据cookie获得购物车信息
        List<TbItem> cartList = getCartListFromCookie(request);
        //判断商品在购物车商品列表中是否存在
        boolean flag = false;
        for(TbItem tbItem:cartList){
            //如果存在数量相加
            if(tbItem.getId().longValue() == itemId){
                flag = true;
                tbItem.setNum(tbItem.getNum() + num);
                //跳出循环
                break;
            }
        }
        //如果商品在购物车商品列表中不存在
        if(!flag){
            //根据商品id查询商品信息。得到一个TbItem对象
            TbItem tbItem = itemService.getItemById(itemId);
            //设置购物车商品数量
            tbItem.setNum(num);
            //取第一张图片
            String image = tbItem.getImage();
            if(StringUtils.isNotBlank(image)){
                tbItem.setImage(image.split(",")[0]);
            }
            //把商品添加到商品列表
            cartList.add(tbItem);
        }
        //写入cookie
        CookieUtils.setCookie(request,response,"cart",JsonUtils.objectToJson(cartList),COOKIE_CART_EXPIRE,true);
        return "cartSuccess";
    }

    /**
     * 从cookie中获取购物车列表的处理
     * @param request
     * @return
     */
    private List<TbItem> getCartListFromCookie(HttpServletRequest request){
        String json = CookieUtils.getCookieValue(request,"cart",true);
        //判断json是否为空
        if(StringUtils.isBlank(json)) {
            return new ArrayList<>();
        }
        //把json转换为商品列表
        List<TbItem> tbItems = JsonUtils.jsonToList(json, TbItem.class);
        return tbItems;
    }

    /**
     * 展示购物车信息
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/cart/cart")
    public String showCartList(HttpServletRequest request,HttpServletResponse response){
        //从cookie中获取购物车列表
        List<TbItem> cartList = getCartListFromCookie(request);
        //判读用户是否为登录状态
        TbUser user = (TbUser) request.getAttribute("user");
        //如果是登录状态
        if(user != null){
            //从cookie中获取购物车列表
            //如果不为空,把cookie中的购物车商品和服务端的购物车商品合并
            cartService.mergeCart(user.getId(),cartList);
            //把cookie中的购物车删除
            CookieUtils.deleteCookie(request,response,"cart");
            cartList = cartService.getCartList(user.getId());
        }
        //把值传递给页面
        request.setAttribute("cartList",cartList);
        return "cart";
    }

    /**
     * 更新购物车商品数量
     * @param itemId
     * @param num
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/cart/update/num/{itemId}/{num}")
    @ResponseBody
    public EmallResult updateCartNum(@PathVariable Long itemId, @PathVariable int num
    , HttpServletRequest request, HttpServletResponse response){
        //判断用户是否登录
        TbUser user = (TbUser) request.getAttribute("user");
        if(user != null){
            cartService.updateCartNum(user.getId(),itemId,num);
            return EmallResult.ok();
        }
        //从cookie中获取购物车列表
        List<TbItem> cartList = getCartListFromCookie(request);
        //遍历商品列表找到对应的商品
        for(TbItem tbItem : cartList){
            if(tbItem.getId().longValue() == itemId){
                //更新数量
                tbItem.setNum(num);
                //跳出循环
                break;
            }
        }
        //把购物车写会cookie
        CookieUtils.setCookie(request,response,"cart",JsonUtils.objectToJson(cartList),COOKIE_CART_EXPIRE,true);
        return EmallResult.ok();
    }

    /**
     * 删除购物车商品
     * @param itemId
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/cart/delete/{itemId}")
    public String deleteCartItem(@PathVariable Long itemId,HttpServletRequest request, HttpServletResponse response){
        //判断用户是否登录
        TbUser user = (TbUser) request.getAttribute("user");
        if(user != null){
            cartService.deleteCartItem(user.getId(),itemId);
            return "redirect:/cart/cart.html";
        }
        //从cookie中获取购物车列表
        List<TbItem> cartList = getCartListFromCookie(request);
        //遍历商品列表找到对应的商品
        for(TbItem tbItem : cartList){
            if(tbItem.getId().longValue() == itemId){
                //删除商品
                cartList.remove(tbItem);
                //跳出循环
                break;
            }
        }
        //把购物车写会cookie
        CookieUtils.setCookie(request,response,"cart",JsonUtils.objectToJson(cartList),COOKIE_CART_EXPIRE,true);
        return "redirect:/cart/cart.html";
    }

}
